package cn.hls.web.controller.base;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import cn.hls.entity.User;
import cn.hls.entity.vo.Msg;
import cn.hls.entity.vo.PageInfo;

/**
 * @fileName: BaseController.java
 * @package: com.bangni.web.controller.base
 * @Description: controller基类
 * @author: yinghui.zhang
 * @email: uuhui@163.com
 * @date: 2015-4-11
 */
@Controller
public class BaseController<T> {

	// 分页模块
	protected PageInfo<T> page = new PageInfo<T>();
	protected Msg msg = new Msg();
	// 传递的数据过滤
	protected String colModel;

	// 记录id集合
	protected String ids;

	private HttpServletRequest request;

	protected ModelAndView mav = null;

	/**
	 * 获取当前登录用户
	 * 
	 * @return
	 */
	public User getCurrentUser(HttpServletRequest request) {
		return (User) request.getSession().getAttribute("currentUser");
	}

	public String getContextRealPath() {
		return request.getSession().getServletContext().getRealPath("/");
	}

	/**
	 * 异常控制
	 */
	@ExceptionHandler(Exception.class)
	@ResponseBody
	@ResponseStatus(value = HttpStatus.OK)
	// 采用200返回
	public ModelAndView handleException(Exception ex, HttpServletRequest request) {
		ex.printStackTrace(); // 开发时控制台显示，发布时移除
		ModelAndView nv = new ModelAndView();
		if (ex instanceof DataIntegrityViolationException) {
			if (ex.getMessage().contains("SQL [n/a]")) {
				nv.addObject("msg", "数据操作失败！");
			} else {
				nv.addObject("msg",ex.getMessage());
			}
		} else {
			nv.addObject("msg", ex.getMessage());
		}
		nv.addObject("success", false);
		return nv;
	}

	/**
	 * 获得request 的参数
	 * 
	 * @param key
	 * @return
	 */
	protected String getRequestParameter(String key) {
		return request.getParameter(key);
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	 

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(true);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}

}
